var Glimit=8;
// 翻页最多显示元素个数
var MaxPageNum = 10;
// 翻页只能显示几个数字
var NumNum = 8;
// 文字位置信息
var WordPositionData;
// cropper
var CropperHandle = false;

// 显示页码使用
var MaxIndex;

var WordIndex;
var WordOperation;


function insertSelect(api, sutraID, selectId){
    sclist = $('#sclist').html();
    var doTtmpl = doT.template(sclist);

    var offset = 0;
    data = {
        'offset': offset,
        'limit': 0,
        'getall': 1,
    }
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: api,
        type: 'GET',
        data: data,
        async: false,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                scid = '#' + selectId
                $(scid).html(doTtmpl(data));
                sscid = '#' + 'sc_' + sutraID;
                $(sscid).attr('selected', 'selected')
            }
            else{
                alert('请求异常, 请刷新')
            }
        },
    });
}


function insertSutrasCategorySelect(sutraID, selectId) {
    api = '/backstage/sutra/category/list';
    insertSelect(api, sutraID, selectId)
}

function insertEditionSelect(sutraID, editionId, selectId) {
    api = '/backstage/sutra/'+ sutraID +'/edition/list?offset=0&limit=0';
    insertSelect(api, editionId, selectId)
}


function pageListAddE(Id, maxNum, index, total, operation){
    if (total <= maxNum || total == 0) {
        return
    }
    pagenums = document.getElementById(Id);
    childrens = pagenums.children;
    
    if (index == 1) {
        for (var i = total; i >= maxNum - 1; i--) {
            aid = '#a' + i
            $(aid).css('display', 'none')
        }
        tailS = document.getElementById('tailS');
        if (!tailS) {
           li = document.createElement('li');
            li.className = 'paginate_button';
            li.id = 'tailS';
            a = document.createElement('a');
            a.innerText = '...';
            li.appendChild(a);
            pagenums.insertBefore(li, childrens[total]); 
        }
        return
    }
    if ((index - 1) % NumNum == 0 && operation=='+') {

        for (var i = index - 1; i >= index - NumNum; i--) {
            aid = '#a' + i
            $(aid).css('display', 'none')
        }
        preS = document.getElementById('preS');
        if (!preS) {
            li = document.createElement('li');
            li.className = 'paginate_button';
            li.id = 'preS';
            a = document.createElement('a');
            a.innerText = '...';
            li.appendChild(a);
            pagenums.insertBefore(li, childrens[1]);
        }
        for (var i = index; i < index + NumNum; i++) {
            aid = '#a' + i
            $(aid).css('display', '')
        }
        if(index + NumNum > total){
            $('#tailS').css('display', 'none')
        }
        $('#preS').css('display', '')
        return
    }
    if (index % NumNum == 0 && operation=='-') {
        for (var i = index + 1; i <= index + NumNum; i++) {
            aid = '#a' + i
            $(aid).css('display', 'none')
        }
        for (var i = index; i > index - NumNum; i--) {
            aid = '#a' + i
            $(aid).css('display', '')
        }
        if(index + NumNum > total){
            $('#tailS').css('display', '')
        }
        if(index == NumNum){
            $('#preS').css('display', 'none')
        }

    }
}


function pageChoice(editionId, index, tmp) {
    sutra_id = getQueryString('sutra_id');
    edition_id = getQueryString('edition_id');
    page = getQueryString('page');
    sutra_id = getQueryString('sutra_id');
    url = "page.html?edition_id=" + editionId;
    url = url + '&sutra_id=' + sutra_id;
    if (index == '+') {
        page = parseInt(page) + 1;
        url = url + '&page=' + page;
    }else if (index == '-') {
        page = parseInt(page) - 1;
        url = url + '&page=' + page;
    }else {
        url = url + '&page=' + index;
    }
    url = url + '&index=' + index;
    window.location.href=url;
}


function pageListCommon(edition_id, offset, limit){
    var dotlist = $('#dotlist').html();
    var res = false;
    var api = '/backstage/sutra/edition/' + edition_id + '/page/list';
    var csrftoken = getCookie('csrftoken');
    data = {
        'offset': offset,
        'limit': limit
    }
    $.ajax({
        url: api,
        type: 'GET',
        async: false,
        dataType: 'json',
        data: data,
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                doTtmpl = doT.template(dotlist);
                $('#main_row').html(doTtmpl(data));
                MaxIndex = data.data["n"];
            }
            else{
                alert('请求异常, 请刷新')
            }
        },
    });
}


function insertPageNum(editionId, perPageNum){
    $('#pagenumsdemo').css('display', '');
    api = '/backstage/sutra/edition/' + editionId;
    var csrftoken = getCookie('csrftoken');
    var n = 10;
    $.ajax({
        url: api,
        type: 'GET',
        data: data,
        async: false,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                total_num = data.data['total_page_num'];
                n = total_num / perPageNum
                if(total_num % perPageNum > 0){
                    n = n + 1
                }
                data.data['n'] = parseInt(n);
                data.data['editionId'] = editionId;
                if(n>0){
                    pagenumslist = $('#pagenumslist').html();
                    doTtmpl = doT.template(pagenumslist);
                    $('#pagenums').html(doTtmpl(data));
                }
            }
            else{
                alert('请求异常, 请刷新')
            }
        },
    });
    pageListAddE('pagenums', MaxPageNum, 1, n)
}

function pageNumLight(editionId, index, maxIndex) {
    old_ac = document.getElementsByClassName('paginate_button active')[0];
    tabindex = old_ac.getAttribute('tabindex')
    if(index=='-'){
        if(tabindex > 1){
            index = parseInt(tabindex) - 1;
            aid = '#a' + index;
            old_ac.className = 'paginate_button';
            $(aid).attr('class', 'paginate_button active');
            pageListAddE(
                'pagenums', MaxPageNum, index, maxIndex, '-')
        }
    }else if(index=='+'){
        if(tabindex < maxIndex){
            index = parseInt(tabindex) + 1;
            old_ac.className = 'paginate_button';
            aid = '#a' + index;
            $(aid).attr('class', 'paginate_button active');
            pageListAddE(
                'pagenums', MaxPageNum, index, maxIndex, '+')
        }           
    }else{
        old_ac.className = 'paginate_button';
        aid = '#a' + index;
        $(aid).attr('class', 'paginate_button active');
    }
}

function pageList(){
    insertSutrasAndEdition();
    edition_id = getQueryString('edition_id');
    page = getQueryString('page');
    sutra_id = getQueryString('sutra_id');
    index = getQueryString('index')
    if(edition_id){
        $('#sutras_category').val(sutra_id);
        insertEditionSelect(sutra_id, false, 'sutras_edition');
        $('#sutras_edition').val(edition_id);
        pageListCommon(edition_id, (page - 1) * Glimit, Glimit);
        insertPageNum(edition_id, Glimit);
        pageNumLight(edition_id, index, MaxIndex)
    }
    $('#sutras_edition').change(function(){
        edition_id = $(this).val();
        sutra_id = $('#sutras_category').val();
        if(edition_id == -1){
            return;
        }
        url = "page.html?edition_id=" + edition_id;
        url = url + '&sutra_id=' + sutra_id;
        url = url + '&page=1';
        url = url + '&index=1'
        window.location.href=url;
    });
}

function insertSutrasAndEdition(){
    insertSutrasCategorySelect(false, 'sutras_category');
    var sutra_id;
    var edition_id;
    $('#sutras_category').change(function(){
        sutra_id = $(this).val();
        insertEditionSelect(sutra_id, false, 'sutras_edition');
    });
}

function editionGet (Id) {
    var category = false;
    var api = '/backstage/sutra/edition/' + Id;
    var csrftoken = getCookie('csrftoken');
    data = {
        'need_num': Glimit,
    }
    $.ajax({
        url: api,
        type: 'GET',
        data: data,
        async: false,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                category = data.data
            }
            else{
                alert('请求异常, 请重试')
            }
        },
    });
    return category
}



function getPageDetailByPageNum(editionId, pageNum){
    var csrftoken = getCookie('csrftoken');
    var res = false;
    api = '/backstage/sutra/edition/page'
    data = {
        'edition_id': editionId,
        'page_num': pageNum,
    }
    $.ajax({
        url: api,
        type: 'GET',
        async: false,
        data: data,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                res = data.data
            }
        },
    });
    return res
}


function getPageDetailByPageId(pageId){
    var csrftoken = getCookie('csrftoken');
    var res = false;
    api = '/backstage/sutra/edition/page'
    data = {
        'page_id': pageId,
    }
    $.ajax({
        url: api,
        type: 'GET',
        async: false,
        data: data,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                res = data.data
            }
        },
    });
    return res
}


function ImgUploadCheck(editionId, EndUpPageNum){
    var res = true;
    for (var i = NumNum - 1; i >= 0; i--) {
        pageNum = EndUpPageNum - i
        data = getPageDetailByPageNum(editionId, pageNum)
        if(data == false){
            res = pageNum
        }
        if (res != true) { break;}
    }
    return res
}


function imgReupload(pageNum) {
    var addId = '#add' + pageNum;
    var imgdivId = '#imgdiv' + pageNum;
    var imgId = '#addimg' + pageNum;
    $(addId).css('display', '')
    $(imgdivId).css('display', 'none')        
}


function addUploadDemo(editionId, EndUpPageNum){
    if (EndUpPageNum) {
        res = ImgUploadCheck(editionId, EndUpPageNum);
        if (res != true) {
            alert('第' + pageNum + "页上传异常请重试")
            imgReupload(pageNum);
            return
        }
    }
    res = editionGet(editionId);
    var dotlist = $('#dotlist').html();
    doTtmpl = doT.template(dotlist);
    $('#main_row').html(doTtmpl(res));
}


function pageCreate(){
    insertSutrasAndEdition();
    $('#sutras_edition').change(function(){
        edition_id = $(this).val();
        if(edition_id == -1){
            return;
        }
        addUploadDemo(edition_id, false); 
    });
}


function pageCreateHandle(editionId, page_num, file){
    var res=false;
    var data = new FormData();
    data.append('edition_id', editionId);
    data.append('page_num', page_num);
    data.append('content_img', file)
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: '/backstage/sutra/edition/page',
        type: 'POST',
        data: data,
        async: false,
        processData: false,
        contentType: false,
        cache: false,
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                res = true
            }
            else{
                alert('请求异常, 请刷新')
            }
        },
    });
    return res
}


function imgPreview(Id, editionId, first){
    if(!first){
        var perAddId = '#add' + (Id - 1)
        data_upload = $(perAddId).attr('data-upload')
        if(data_upload != 1){
            alert('请先传前一张图')
            return
        }
    }
    finputId = '#f' + Id;
    $(finputId).trigger("click");
    var upimg = document.querySelector(finputId);
    upimg.addEventListener('change', function(e){
        var files = this.files;
        if(!files.length){
            return
        }
        var file = files[0];
        var reader = new FileReader();
        if(!/image\/\w+/.test(file.type)){
            alert("请确保文件为图像类型");
            return false;
        }
        var addId = '#add' + Id;
        var imgdivId = '#imgdiv' + Id;
        var imgId = '#addimg' + Id;
        reader.onload = function(e){
            $(addId).css('display', 'none')
            $(imgdivId).css('display', '')        
            $(imgId).attr('src', e.target.result);
            $(imgId).attr('class', 'editionimg');
        }
        reader.readAsDataURL(file);
        res = pageCreateHandle(editionId, Id, $(finputId)[0].files[0])
        if (res) {
            $(addId).attr('data-upload', '1')
        }
    });    
}



function pageUpdate(){
    pageId = getQueryString('page_id');
    res = getPageDetailByPageId(pageId);
    $('#edition_name').val(res.edition_name);
    $('#page_num').val(res.page_num);
    $('#page_img_url').attr('href', res.original_cimg_url);
    $('#update_page').on('click', function(){
        var data = new FormData();
        data.append('edition_id', res.edition_id);
        data.append('page_num', $('#page_num').val());
        data.append('content_img', $('#page_img')[0].files[0])
        var csrftoken = getCookie('csrftoken');
        $.ajax({
            url: '/backstage/sutra/edition/page/' + pageId,
            type: 'PUT',
            data: data,
            async: false,
            processData: false,
            contentType: false,
            cache: false,
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data, status){
                if(data.status==200){
                    alert('修改成功');
                    window.location.reload()
                }else if (data.status==409) {
                    alert('页面已经完成定位');
                }else{
                    alert('页面不存在');
                }
            },
            error: function(){
                alert('请求异常');
            },
        });
    });
}

function pageDelete(pageId) {
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: '/backstage/sutra/edition/page/' + pageId,
        type: 'DELETE',
        async: false,
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status == 200){
                alert('删除成功');
                window.location.reload()
            }else if (data.status==409) {
                alert('页面已经完成定位');
            }else{
                alert('页面不存在');
            }
        },
        error: function(){
            alert('请求异常');
        },
    });
}

function pageWordLocate(){
    pageId = getQueryString('page_id');
    editionId = getQueryString('edition_id');
    res = getPageDetailByPageId(pageId);
    $('#edition_name').val(res.edition_name);
    $('#page_num').val(res.page_num);
    $('#page_img').attr('src', res.original_cimg_url);
    $('#page_content').val(res.content);
    var csrftoken = getCookie('csrftoken');
    dotList = $('#dotlist').html();
    var doTtmpl = doT.template(dotList);
    data = {
        'edition_id': editionId,
    }

    $.ajax({
        url: '/backstage/sutra/edition/page/' + pageId+ '/words/position',
        type: 'GET',
        data: data,
        async: false,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                WordPositionData = data.data;
                if (data.data.status == 0 && data.data.words.length > 0) {
                    $('#locate_commit').css('display', '');
                }
                $('#locate_res').html(doTtmpl(WordPositionData));
            }
            else{
                alert('请求异常, 请重试')
            }
        },
    });
}


function pageWordLocateCommit() {
    msg = '您确定要提交吗?提交后将不能再次修改'
    if(confirm(msg)!=true){
        return
    }
    page_id = getQueryString('page_id');
    edition_id = getQueryString('edition_id');
    var csrftoken = getCookie('csrftoken');
    data = {
        'page_id': page_id,
        'edition_id': edition_id,
        'extra_w': JSON.stringify(WordPositionData.extra_w),
        'words': JSON.stringify(WordPositionData.words),
        'word_imgurl': JSON.stringify(WordPositionData.word_imgurl),
    }
    $.ajax({
        url: '/backstage/sutra/edition/page/' + pageId+ '/words/position',
        type: 'POST',
        data: data,
        async: false,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status==200){
                alert('提交成功');
                location.reload();
            }
            else{
                alert('请求异常, 请重试')
            }
        },
    }); 
}


function wordsDelete(index){
    dotList = $('#dotlist').html();
    var doTtmpl = doT.template(dotList);
    tmp_word_imgurl = [];
    tmp_words = [];
    tmp_extra_w = [];
    gwords = WordPositionData.words
    gword_imgurl = WordPositionData.word_imgurl
    gextra_w = WordPositionData.extra_w
    for (var i = 0; i < gword_imgurl.length; i++) {
        if (i != index) {
            tmp_word_imgurl.push(gword_imgurl[i]);
        }
    }
    for (var i = 0; i < gwords.length - 1; i++) {
        tmp_words.push(gwords[i]);
    }
    tmp_extra_w.push(gwords[i])
    for (var i = 0; i < gextra_w.length; i++) {
        tmp_extra_w.push(gextra_w[i]);
    }
    WordPositionData.word_imgurl = tmp_word_imgurl;
    WordPositionData.words = tmp_words;
    WordPositionData.extra_w = tmp_extra_w;
    $('#locate_res').html(doTtmpl(WordPositionData));
}

function wordsCreate(index_pre, data){
    $('#screenshot_upload').css('display', 'none');
    dotList = $('#dotlist').html();
    var doTtmpl = doT.template(dotList);
    tmp_word_imgurl = [];
    gword_imgurl = WordPositionData.word_imgurl
    gextra_w = WordPositionData.extra_w;
    for (var i = 0; i <= gword_imgurl.length; i++) {
        if (i == index_pre) {
            tmp_word_imgurl.push(data.word_url);
        }else if (i < index_pre) {
            tmp_word_imgurl.push(gword_imgurl[i]);
        }else {
            tmp_word_imgurl.push(gword_imgurl[i - 1]);
        }
    }
    WordPositionData.words.push(gextra_w[0]);
    WordPositionData.extra_w.splice(0, 1);
    WordPositionData.word_imgurl = tmp_word_imgurl;
    $('#locate_res').html(doTtmpl(WordPositionData));
}

function wordsUpdate(index, data){
    $('#screenshot_upload').css('display', 'none');
    dotList = $('#dotlist').html();
    var doTtmpl = doT.template(dotList);
    tmp_word_imgurl = [];
    gword_imgurl = WordPositionData.word_imgurl

    for (var i = 0; i < gword_imgurl.length; i++) {
        if (i == index) {
            tmp_word_imgurl.push(data.word_url);
        }else {
            tmp_word_imgurl.push(gword_imgurl[i]);
        }
    }
    WordPositionData.word_imgurl = tmp_word_imgurl;
    $('#locate_res').html(doTtmpl(WordPositionData));
}


function wordImgUpload() {
    canvasData= CropperHandle.getCroppedCanvas()
    Base64Img = canvasData.toDataURL();
    img = Base64Img.split(';base64,');
    data = {
        'base64img': img[1],
        'page_id': pageId,
        'edition_id': editionId,
    };
    var csrftoken = getCookie('csrftoken');
    $.ajax('/backstage/sutra/word/image/upload', {
        method: "POST",
        data: data,
        async: false,
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function (data, status) {
            if(data.status==200){
                if(WordOperation == 'update'){
                    wordsUpdate(WordIndex, data.data);
                }else {
                    wordsCreate(WordIndex, data.data);
                }
                CropperHandle.destroy();
            }else {
                alert('Upload error');
            }
        },
        error: function () {
            alert('Upload error');
        }
    });
}


function screenshot(index, operation){
    WordIndex = index;
    WordOperation = operation;
    pageId = getQueryString('page_id');
    editionId = getQueryString('edition_id');
    image = document.getElementById('page_img');
    if (CropperHandle) {
        CropperHandle.destroy();
    }
    CropperHandle = new Cropper(image, {
        aspectRatio: NaN,
        crop: function(e) {}
    });
    $('#screenshot_upload').css('display', '');
} 

$(document).ready(function(){
    operation = getQueryString('operation');
    switch(operation)
    {
        case 'list':
            pageList();
            break;
        case 'create':
            pageCreate();
            break;
        case 'update':
            pageUpdate();
            break;
        case 'recog':
            pageRecog();
            break;
        case 'locate':
            pageWordLocate();
            break;
        default:
            pageList();
            break;
    }
})